﻿using Sunboxsoft.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sunboxsoft.ASMS.Server.Domain.Service
{
    public class UpdateService
    {
        public ServiceResult UpdateAutomobile(Guid id, Entity.EAutomobile automobile)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                Entity.EAutomobile entity = dbContext.Set<Entity.EAutomobile>().SingleOrDefault(p => p.Id == id);
                if (entity == null)
                {
                    return new ServiceResult(1, "object not exist!");
                }

                entity.BoughtDate = automobile.BoughtDate;
                entity.Brand = automobile.Brand;
                entity.EIN = automobile.EIN;
                entity.EngineType = automobile.EngineType;
                entity.InsuranceCompany = automobile.InsuranceCompany;
                entity.InsuranceExpirationDate = automobile.InsuranceExpirationDate;
                entity.InsuranceNumber = automobile.InsuranceNumber;
                entity.LPN = automobile.LPN;
                entity.Maker = automobile.Maker;
                entity.Model = automobile.Model;
                entity.NextAnnualSurveyDate = automobile.NextAnnualSurveyDate;
                entity.NextMaintenanceDate = automobile.NextMaintenanceDate;
                entity.NextReplaceTireDate = automobile.NextReplaceTireDate;
                entity.Owner = automobile.Owner;
                entity.OwnerTelephone = automobile.OwnerTelephone;
                entity.Series = automobile.Series;
                entity.VIN = automobile.VIN;
                dbContext.Entry<Entity.EAutomobile>(entity).State = System.Data.Entity.EntityState.Modified;

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("UpdateAutomobile error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        /// <summary>
        /// 更新预约单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="bookingBill"></param>
        /// <param name="serviceArray"></param>
        /// <returns></returns>
        public ServiceResult UpdateBookingBill(Guid id, Entity.EBookingBill bookingBill, Entity.EBookingService[] serviceArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                Entity.EBookingBill existBill = dbContext.Set<Entity.EBookingBill>().SingleOrDefault(p => p.Id == id);
                if (existBill == null)
                {
                    return new ServiceResult(1, "object not exist!");
                }

                existBill.Memo = bookingBill.Memo;
                existBill.TargetDate = bookingBill.TargetDate;
                existBill.SalesManagerId = bookingBill.SalesManagerId;
                dbContext.Entry<Entity.EBookingBill>(existBill).State = System.Data.Entity.EntityState.Modified;

                dbContext.Database.ExecuteSqlCommand("delete from ASMS_BookingService where BillId={0}", existBill.Id);

                for (int index = 0; index < serviceArray.Length; index++)
                {
                    serviceArray[index].BillId = existBill.Id;
                    serviceArray[index].Id = Guid.NewGuid();
                    dbContext.Set<Entity.EBookingService>().Add(serviceArray[index]);
                }

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("UpdateBookingBill error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        /// <summary>
        /// 更新客户资料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="customer"></param>
        /// <returns></returns>
        public ServiceResult UpdateCustomer(Guid id, Entity.ECustomer customer)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                Entity.ECustomer entity = dbContext.Set<Entity.ECustomer>().SingleOrDefault(p => p.Id == id);
                if (entity == null)
                {
                    return new ServiceResult(1, "object not exist!");
                }

                if (!string.IsNullOrEmpty(customer.IdNumber))
                {
                    if (dbContext.Set<Entity.ECustomer>().Where(p => p.Id != id && p.IdNumber == customer.IdNumber).Select(p => p.Id).Count() > 0)
                    {
                        return new ServiceResult(1, "身份证已经存在!");
                    }
                }

                entity.Name = customer.Name;
                entity.IdNumber = customer.IdNumber;
                entity.IsCredit = customer.IsCredit;
                entity.SalesManagerId = customer.SalesManagerId;
                entity.Birthday = customer.Birthday;
                entity.Country = customer.Country;
                entity.Province = customer.Province;
                entity.City = customer.City;
                entity.District = customer.District;
                entity.Address = customer.Address;
                entity.Wechat = customer.Wechat;
                entity.QQ = customer.QQ;
                entity.EMail = customer.EMail;
                dbContext.Entry<Entity.ECustomer>(entity).State = System.Data.Entity.EntityState.Modified;

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("UpdateCustomer error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        public ServiceResult UpdatePackage(Guid id, Entity.EPackage package, Entity.EPackageItem[] itemArray, Entity.ESalesPrice[] priceArray, Entity.EPackageScope[] scopeArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;
                Entity.EPackage entity = dbContext.Set<Entity.EPackage>().SingleOrDefault(p => p.Id == id);
                if (entity == null)
                {
                    return new ServiceResult(1, "object not exist!");
                }

                entity.Name = package.Name;
                entity.PackageAccessibility = package.PackageAccessibility;
                entity.Price = package.Price;
                entity.BusinessId = package.BusinessId;
                entity.Description = package.Description;
                entity.Duration = package.Duration;
                entity.DurationType = package.DurationType;
                entity.ExpiringDate = package.ExpiringDate;
                entity.RebuyCount = package.RebuyCount;
                entity.SalesCommission = package.SalesCommission;
                entity.SalesCommissionType = package.SalesCommissionType;
                entity.StartSaleTime = package.StartSaleTime;
                entity.StationId = package.StationId;
                entity.Status = Constant.CommonStatus.Disabled;
                entity.StopSaleTime = package.StopSaleTime;
                entity.TechnicianCommission = package.TechnicianCommission;
                entity.TechnicianCommissionType = package.TechnicianCommissionType;

                dbContext.Database.ExecuteSqlCommand("delete from ASMS_PackageItem where PackageId={0}", id);
                dbContext.Database.ExecuteSqlCommand("delete from ASMS_PackageScope where PackageId={0}", id);
                dbContext.Database.ExecuteSqlCommand("delete from ASMS_SalesPrice where TargetId={0}", id);

                if (priceArray != null && priceArray.Length > 0)
                {
                    for (int index = 0; index < priceArray.Length; index++)
                    {
                        Entity.ESalesPrice item = priceArray[index];
                        item.Id = Guid.NewGuid();
                        item.TargetId = id;
                        item.TargetType = Constant.SalePriceTargetTypes.Package;
                        item.CreatedTime = now;
                        item.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                        item.Status = Constant.CommonStatus.Enabled;
                        dbContext.Set<Entity.ESalesPrice>().Add(item);
                    }
                }

                decimal marketValue = 0;
                if (itemArray != null && itemArray.Length > 0)
                {
                    for (int index = 0; index < itemArray.Length; index++)
                    {
                        Entity.EPackageItem item = itemArray[index];
                        item.Id = Guid.NewGuid();
                        item.PackageId = id;
                        marketValue += item.MarketPrice;
                        dbContext.Set<Entity.EPackageItem>().Add(item);
                    }
                }

                if (scopeArray != null && scopeArray.Length > 0)
                {
                    for (int index = 0; index < scopeArray.Length; index++)
                    {
                        Entity.EPackageScope scope = scopeArray[index];
                        scope.Id = Guid.NewGuid();
                        scope.PackageId = id;
                        dbContext.Set<Entity.EPackageScope>().Add(scope);
                    }
                }
                else
                {
                    // 创建一个默认的适合全部的范围项
                    Entity.EPackageScope scope = new Entity.EPackageScope();
                    scope.Id = Guid.NewGuid();
                    scope.PackageId = id;
                    dbContext.Set<Entity.EPackageScope>().Add(scope);
                }
                entity.MarketPrice = marketValue;
                dbContext.Entry<Entity.EPackage>(entity).State = System.Data.Entity.EntityState.Modified;

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("UpdatePackage error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        /// <summary>
        /// 更新派工单到完成状态
        /// </summary>
        /// <returns></returns>
        public ServiceResult UpdateWorkingBillToFinished(Guid maintenanceBillId, Guid maintenanceBillServiceItemId)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                Entity.EWorkingBill workingBill = dbContext.Set<Entity.EWorkingBill>().SingleOrDefault(p => p.MaintenanceBillId == maintenanceBillId && p.MaintenanceBillServiceItemId == maintenanceBillServiceItemId
                     && p.Status == Constant.WorkingBillStatus.Enabled);
                if (workingBill == null)
                {
                    return new ServiceResult(1, "object is not exist! ");
                }

                Entity.EMaintenanceBill maintenanceBill = dbContext.Set<Entity.EMaintenanceBill>().Single(p => p.Id == workingBill.MaintenanceBillId);
                if (maintenanceBill == null)
                {
                    return new ServiceResult(1, "maintenanceBill is not exist! ");
                }

                Entity.EMaintenanceBillServiceItem maintenanceBillServiceItem = dbContext.Set<Entity.EMaintenanceBillServiceItem>().Single(p => p.Id == maintenanceBillServiceItemId);
                if (maintenanceBill == null)
                {
                    return new ServiceResult(1, "maintenanceBillServiceItem is not exist! ");
                }

                DateTime now = DateTime.Now;
                workingBill.Status = Constant.WorkingBillStatus.Finished;
                workingBill.FinishedTime = now;
                dbContext.Entry<Entity.EWorkingBill>(workingBill).State = System.Data.Entity.EntityState.Modified;

                if (maintenanceBill.ServiceItemCount > 1 && dbContext.Set<View.VMaintenanceBillServiceItem>().Where(p => p.MaintenanceBillId == workingBill.MaintenanceBillId && p.ActualFinishedTime == null).Select(p => p.Id).Count() > 1)
                {
                    #region 还有多个项目没有派工或竣工
                    if (maintenanceBill.ServiceItemStatus == Constant.MaintenanceBillStatus.ServiceItemStatus.Working)
                    {
                        maintenanceBill.ServiceItemStatus = Constant.MaintenanceBillStatus.ServiceItemStatus.PartialWorking;
                    }
                    #endregion
                    maintenanceBill.Status = Constant.MaintenanceBillStatus.Working;
                }
                else
                {
                    #region 刚好只有一个工作项目没有竣工
                    maintenanceBill.ServiceItemStatus = Constant.MaintenanceBillStatus.ServiceItemStatus.Finished;

                    if (maintenanceBill.MaterialStatus == Constant.MaintenanceBillStatus.MaterialStatus.Finished)
                    {
                        // 不需要领料或全部已领料，更新为带结算状态
                        maintenanceBill.Status = Constant.MaintenanceBillStatus.WaitSettling;
                    }
                    else
                    {
                        maintenanceBill.Status = Constant.MaintenanceBillStatus.Working;
                    }
                    #endregion
                }
                dbContext.Entry<Entity.EMaintenanceBill>(maintenanceBill).State = System.Data.Entity.EntityState.Modified;

                maintenanceBillServiceItem.Status = Constant.MaintenanceBillServiceItemStatus.Finished;
                dbContext.Entry<Entity.EMaintenanceBillServiceItem>(maintenanceBillServiceItem).State = System.Data.Entity.EntityState.Modified;

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("UpdateWorkingBillToFinished error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        public ServiceResult UpdateStockThresholdValue(Entity.EStockThresholdValue stockThresholdValue)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                if (stockThresholdValue.Id == Guid.Empty)
                {
                    return new ServiceResult(1, "无效的Id");
                }

                Entity.EStockThresholdValue existStockThresholdValue = dbContext.Set<Entity.EStockThresholdValue>().SingleOrDefault(p => p.Id == stockThresholdValue.Id);

                if (existStockThresholdValue == null)
                {
                    return new ServiceResult(1, "object not exist!");
                }

                DateTime now = DateTime.Now;
                existStockThresholdValue.Value = stockThresholdValue.Value;
                existStockThresholdValue.CreatedTime = now;
                existStockThresholdValue.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                existStockThresholdValue.Status = Constant.CommonStatus.Enabled;

                dbContext.Entry<Entity.EStockThresholdValue>(existStockThresholdValue).State = System.Data.Entity.EntityState.Modified;

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("UpdateThresholdValue error,ex:{0}", ex));
                    return new ServiceResult(1, ex.ToString());
                }
            }
        }

        /// <summary>
        /// 更新仓库
        /// </summary>
        /// <param name="id"></param>
        /// <param name="warehouse"></param>
        /// <returns></returns>
        public ServiceResult UpdateWarehouse(Guid id, Entity.EWarehouse warehouse)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                Entity.EWarehouse entity = dbContext.Set<Entity.EWarehouse>().SingleOrDefault(p => p.Id == id);
                if (entity == null)
                {
                    return new ServiceResult(1, "object not exist!");
                }

                entity.Address = warehouse.Address;
                entity.City = warehouse.City;
                entity.ContactName = warehouse.ContactName;
                entity.ContactTelephone = warehouse.ContactTelephone;
                entity.Country = warehouse.Country;
                entity.District = warehouse.District;
                entity.Description = warehouse.Description;
                entity.Province = warehouse.Province;
                entity.Name = warehouse.Name;
                dbContext.Entry<Entity.EWarehouse>(entity).State = System.Data.Entity.EntityState.Modified;

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("UpdateWarehouse error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

    }
}
